package com.ruoyi.business.controller;

import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.business.domain.vo.StationVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.Station;
import com.ruoyi.business.service.IStationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 城市管理Controller
 * 
 * @author ruoyi
 * @date 2025-03-06
 */
@RestController
@RequestMapping("/base/station")
public class StationController extends BaseController
{
    @Autowired
    private IStationService stationService;

    /**
     * 查询城市管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:station:list')")
    @GetMapping("/list")
    public TableDataInfo list(Station station)
    {
        startPage();
        List<Station> list = stationService.selectStationList(station);
        return getDataTable(list);
    }

    /**
     * 导出城市管理列表
     */
    @PreAuthorize("@ss.hasPermi('base:station:export')")
    @Log(title = "城市管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Station station)
    {
        List<Station> list = stationService.selectStationList(station);
        ExcelUtil<Station> util = new ExcelUtil<Station>(Station.class);
        util.exportExcel(response, list, "城市管理数据");
    }

    /**
     * 导入城市列表
     */
    @PreAuthorize("@ss.hasPermi('base:station:add')")
    @Log(title = "城市管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importExcel")
    public AjaxResult importExcel(MultipartFile file) throws Exception {
        ExcelUtil<StationVo> util = new ExcelUtil<>(StationVo.class);
        List<StationVo> vos = util.importExcel(file.getInputStream());
        
        // 用于收集错误数据
        List<StationVo> errorList = new ArrayList<>();
        // 用于收集有效数据
        List<Station> validStations = new ArrayList<>();
        
        int rowNum = 2; // Excel从第2行开始（第1行是表头）
        for (StationVo vo : vos) {
            boolean isValid = true;
            String errorMsg = null;
            
            // 基本数据验证
            if (vo.getName() == null || vo.getName().trim().isEmpty()) {
                errorMsg = "城市名称不能为空";
                isValid = false;
            }
            
            // 检查名称是否已存在
            if (isValid) {
                Station existName = stationService.selectStationByName(vo.getName());
                if (existName != null) {
                    errorMsg = "城市名称[" + vo.getName() + "]已存在";
                    isValid = false;
                }
            }
            
            // 如果数据有效，添加到有效列表
            if (isValid) {
                Station station = new Station();
                station.setId(vo.getId());
                station.setName(vo.getName());
                station.setNamePinyin(vo.getNamePinyin());
                station.setNamePy(vo.getNamePy());
                
                validStations.add(station);
            } else {
                // 创建错误数据对象
                vo.setRowNum(rowNum);
                vo.setErrorMsg(errorMsg);
                errorList.add(vo);
            }
            
            rowNum++;
        }
        
        // 批量插入有效数据
        int successCount = 0;
        for (Station station : validStations) {
            try {
                int result = stationService.insertStation(station);
                if (result > 0) {
                    successCount++;
                }
            } catch (Exception e) {
                // 记录插入失败的数据
                StationVo errorVo = new StationVo();
                errorVo.setRowNum(0); // 系统错误
                errorVo.setName(station.getName());
                errorVo.setNamePinyin(station.getNamePinyin());
                errorVo.setNamePy(station.getNamePy());
                errorVo.setErrorMsg("数据库插入失败: " + e.getMessage());
                errorList.add(errorVo);
                
                // 记录详细错误日志
                logger.error("插入城市数据失败: " + e.getMessage(), e);
            }
        }
        
        // 返回结果，包含完整的错误数据
        if (!errorList.isEmpty()) {
            AjaxResult result = AjaxResult.error("部分数据导入失败", errorList);
            result.put("successCount", successCount);
            return result;
        } else {
            return AjaxResult.success("成功导入" + successCount + "条数据");
        }
    }

    /**
     * 下载城市导入模板
     */
    @PreAuthorize("@ss.hasPermi('base:platform:export')")
    @Log(title = "城市管理", businessType = BusinessType.EXPORT)
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        stationService.downloadTemplate(response);
    }

    /**
     * 获取城市管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('base:station:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(stationService.selectStationById(id));
    }

    /**
     * 新增城市管理
     */
    @PreAuthorize("@ss.hasPermi('base:station:add')")
    @Log(title = "城市管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Station station)
    {
        station.setId(IdUtil.getSnowflakeNextId());
        return toAjax(stationService.insertStation(station));
    }

    /**
     * 修改城市管理
     */
    @PreAuthorize("@ss.hasPermi('base:station:edit')")
    @Log(title = "城市管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Station station)
    {
        return toAjax(stationService.updateStation(station));
    }

    /**
     * 删除城市管理
     */
    @PreAuthorize("@ss.hasPermi('base:station:remove')")
    @Log(title = "城市管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(stationService.deleteStationByIds(ids));
    }

    /**
     * 清空城市数据
     */
    @PreAuthorize("@ss.hasPermi('base:station:remove')")
    @Log(title = "城市管理", businessType = BusinessType.CLEAN)
    @PostMapping("/clear")
    public AjaxResult clear(@RequestBody Map<String, String> passwordMap)
    {
        String password = passwordMap.get("password");
        System.out.println("密码：" + password);
        // 验证当前用户密码
        if (!SecurityUtils.matchesPassword(password, SecurityUtils.getLoginUser().getPassword()))
        {
            return AjaxResult.error("密码验证失败");
        }
        return toAjax(stationService.clearStation());
    }

    /**
     * 导出导入错误数据 - 显示ID列和错误原因列
     */
    @PreAuthorize("@ss.hasPermi('base:station:export')")
    @Log(title = "城市管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportErrorData")
    public void exportErrorData(HttpServletResponse response, @RequestParam(required = false) String errorData) throws IOException {
        List<StationVo> errorDataList = new ArrayList<>();
        
        if (StringUtils.hasText(errorData)) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                List<Map<String, Object>> dataList = mapper.readValue(errorData, new TypeReference<List<Map<String, Object>>>() {});
                
                for (Map<String, Object> item : dataList) {
                    StationVo stationVo = new StationVo();
                    
                    // 设置基本字段
                    stationVo.setName(item.get("name") != null ? item.get("name").toString() : null);
                    stationVo.setNamePinyin(item.get("namePinyin") != null ? item.get("namePinyin").toString() : null);
                    stationVo.setNamePy(item.get("namePy") != null ? item.get("namePy").toString() : null);
                    
                    // 处理ID字段
                    if (item.get("id") != null) {
                        try {
                            stationVo.setId(Long.parseLong(item.get("id").toString()));
                        } catch (Exception e) {
                            logger.warn("解析ID失败，将生成新ID: " + e.getMessage());
                            stationVo.setId(IdUtil.getSnowflakeNextId());
                        }
                    } else {
                        stationVo.setId(IdUtil.getSnowflakeNextId());
                    }
                    
                    // 处理行号字段
                    if (item.get("rowNum") != null) {
                        try {
                            stationVo.setRowNum(Integer.parseInt(item.get("rowNum").toString()));
                        } catch (Exception e) {
                            stationVo.setRowNum(0);
                        }
                    }
                    
                    // 设置错误信息
                    stationVo.setErrorMsg(item.get("errorMsg") != null ? item.get("errorMsg").toString() : null);
                    
                    errorDataList.add(stationVo);
                }
            } catch (Exception e) {
                logger.error("解析错误数据失败", e);
            }
        }
        
        stationService.exportErrorData(response, errorDataList);
    }
}
